package com.turbo.boot.crawler.spider.worker.impl.quota;

import com.alibaba.fastjson.JSON;
import com.turbo.boot.crawler.dao.dal.CrawlerResultDal;
import com.turbo.boot.crawler.dao.entity.CrawlerResultEntity;
import com.turbo.boot.crawler.spider.worker.BaseTurboCrawlerPageParser;
import com.xuxueli.crawler.annotation.PageFieldSelect;
import com.xuxueli.crawler.annotation.PageSelect;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 描述
 *
 * @author wuyn
 * @since 2024/4/19
 */
@Service("sinaExchangeRateCrawlerPageParser")
public class SinaExchangeRateCrawlerPageParser extends BaseTurboCrawlerPageParser<SinaExchangeRateCrawlerPageParser.PageVo> {


    @Resource
    private CrawlerResultDal crawlerResultDal;



    @Override
    public void parse(Document html, Element pageVoElement, PageVo pageVo) {
        // 解析封装 PageVo 对象
        String pageUrl = html.baseUri();
        if (StringUtils.isEmpty(pageVo.getCode())) {
            return;
        }
        System.out.println(pageUrl + "：" + pageVo.toString());
        // 处理业务代码

        CrawlerResultEntity entity = buildCrawlerResultEntity();
        entity.setQuotaCode(pageVo.getCode());
        entity.setQuotaName(pageVo.getName());
        entity.setQuotaValue(pageVo.getLastestPrice().replace("↓", "").replace("↑", ""));
        entity.setCollectedAt(new Date());

        crawlerResultDal.insert(entity);
    }


    @Setter
    @Getter
    @PageSelect(cssQuery = "#tbl_wrap > table > tbody > tr")
    public static class PageVo {

        @PageFieldSelect(cssQuery = "th.sort_down")
        private String code;

        @PageFieldSelect(cssQuery = "th:nth-child(2) > a")
        private String name;

        @PageFieldSelect(cssQuery = "td:nth-child(3)")
        private String lastestPrice;


        @PageFieldSelect(cssQuery = "td:nth-child(4)")
        private String trend;

        @PageFieldSelect(cssQuery = "td:nth-child(5)")
        private String rising;


        @PageFieldSelect(cssQuery = "td:nth-child(6)")
        private String openingPrice;


        @PageFieldSelect(cssQuery = "td:nth-child(7)")
        private String highestPrice;


        @PageFieldSelect(cssQuery = "td:nth-child(8)")
        private String lowestPrice;


        @PageFieldSelect(cssQuery = "td:nth-child(9)")
        private String value;


        @PageFieldSelect(cssQuery = "td:nth-child(10)")
        private String yesterdayPrice;


        @PageFieldSelect(cssQuery = "td:nth-child(11)")
        private String buyingPrice;


        @PageFieldSelect(cssQuery = "td:nth-child(12)")
        private String sellingPrice;


        @Override
        public String toString() {
            return JSON.toJSONString(this);
        }
    }
}
